package com.lcykcl.ttgen;

import java.util.ArrayList;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends ListActivity {
	
	/** Items entered by the user is stored in this ArrayList variable */
    private ArrayList<String> selected = new ArrayList<String>();
    
    /** Declaring an ArrayAdapter to set items to ListView */
    private ArrayAdapter<String> adapter;
    
    private AutoCompleteTextView mCodeView;
    
    private DataRetriever dbHelper;
    
    private String courseCode;
    
    public final static String COURSE_URL = "com.lcykcl.ttgen.COURSE_URL";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);	    
		courseSelectedListView();
    }
    
  //pass for now! (I want to change the size of the box that contains selected course informations X_X! )  
    public void courseSelectedListView() {
		
		dbHelper = new DataRetriever(this);
        dbHelper.createDatabase();
        dbHelper.open();
		
		setContentView(R.layout.activity_main);
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, selected);
		setListAdapter(adapter);
		
		 //mCourseView = (TextView) findViewById(R.id.course_code);
	     mCodeView = (AutoCompleteTextView) findViewById(R.id.code_name);

	        // Create an ItemAutoTextAdapter for the State Name field,
	        // and set it as the OnItemClickListener for that field.
	        ItemAutoTextAdapter autoTextAdapter = this.new ItemAutoTextAdapter(dbHelper);
	        
	        mCodeView.setAdapter(autoTextAdapter);
	        mCodeView.setOnItemClickListener(autoTextAdapter);
	        
	        ListView lv = getListView();
	        
	        lv.setOnItemClickListener(new OnItemClickListener() {
	        	public void onItemClick(AdapterView<?> parent, View view,
	                    int position, long id) {
	                     
	                    // selected item 
	                    courseCode = ((TextView) view).getText().toString();
	                    initiatePopupWindow(); 
	            }
	        });
	}
    
    private PopupWindow pwindo;
    private Button btnClosePopup;
   // private Button btnLink;

    @SuppressWarnings("deprecation")
    private void initiatePopupWindow() {
    	
	    try {
		     LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		     View layout = inflater.inflate(R.layout.main_course_popup, (ViewGroup) findViewById(R.id.popup_element));
		    
		     //I think I should talk about this width....:(
		     pwindo = new PopupWindow(layout,LayoutParams.WRAP_CONTENT, 370, true);
		     pwindo.setBackgroundDrawable(new BitmapDrawable());
		     pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
		     
		     TextView popupTitle = (TextView) layout.findViewById(R.id.popupTitle);
             popupTitle.setText(courseCode);

             TableLayout infoTable = (TableLayout) layout.findViewById(R.id.courseInfoTable);
             setTableContent(infoTable);

		     btnClosePopup = (Button) layout.findViewById(R.id.btn_close_popup);
		    // btnLink = (Button) layout.findViewById(R.id.btnCourseLink);
		     
		     btnClosePopup.setOnClickListener(closePopupClicklistener);
		     //btnLink.setOnClickListener(courseLinkClicklistener);
	
	     } catch (Exception e) {
	    	 e.printStackTrace();
	     }
     }
    

    private OnClickListener closePopupClicklistener = new OnClickListener() {
 	    public void onClick(View v) {
 	    	pwindo.dismiss();
 	    }
     };
   
    
    
     public void showCourseDescription(View view) {
    	    Intent intent = new Intent(this, CourseURLActivity.class);
    	    String url = getCourseUrl();
    	    intent.putExtra(COURSE_URL, url);
    	    startActivity(intent);
    	}
     
     
     
     private String getCourseUrl(){
    	 
    	 return (String)dbHelper.getCourseInfo(courseCode).get(0);
     }
	
    
    private void setTableContent(TableLayout infoTable){
    	
    	TableRow tableHead = new TableRow(this);
        tableHead.setId(0);
        tableHead.setBackgroundColor(Color.GRAY);
        tableHead.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	     
        setTableValue(tableHead, 1, "Section");
        setTableValue(tableHead, 2, "Time");
        setTableValue(tableHead, 3, "Location");
        setTableValue(tableHead, 4, "Instructor");
         
        infoTable.addView(tableHead, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    	
    	Cursor cursor = (Cursor)dbHelper.getCourseInfo(courseCode).get(1);
    	Integer count = 0;
    	while (cursor.moveToNext()) {
	    	String sec = cursor.getString(2) + cursor.getString(3);
	    	String time = cursor.getString(4);
	    	String loc = cursor.getString(5);
	    	String inst = cursor.getString(6);
	    	
	    	// Create the table row
	    	TableRow tableRow = new TableRow(this);
	    	if(count % 2 != 0) tableRow.setBackgroundColor(Color.GRAY);
	    	else tableRow.setBackgroundColor(Color.BLACK);
	    	tableRow.setId(100 + count);
	    	tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	
	    	//Create columns to add as table data
	
	    	setTableValue(tableRow, 200 + count, sec);
	    	setTableValue(tableRow, 200 + count, time);
	    	setTableValue(tableRow, 200 + count, loc);
	    	setTableValue(tableRow, 200 + count, inst);
	    	
	    	// finally add this to the table row
	    	infoTable.addView(tableRow, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	    	count++;
    	}
    }
    
    private void setTableValue(TableRow tableHead, Integer id, String text) {
    	TextView label = new TextView(this);
    	label.setId(id);
        label.setText(text); // set the text for the header 
        label.setTextColor(Color.WHITE); // set the color
        //label.setPadding(5, 5, 5, 5); // set the padding (if required)
        tableHead.addView(label); // add the column to the table row here
    }
    
    
	public void courseDeleteListView() {
		setContentView(R.layout.activity_main_delete);
	    Button btnDel = (Button) findViewById(R.id.btnDel);
	    
	    // Reference: http://wptrafficanalyzer.in/blog/deleting-selected-items-from-listview-in-android/
	    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, selected);
	    //ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, selected);
	    
	    /** Defining a click event listener for the button "Delete" */
	    OnClickListener listenerDel = new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		deleteConfirmDialog();
	    	}
	    };  
	    
	    /** Setting the event listener for the delete button */
	    btnDel.setOnClickListener(listenerDel);    

	    /** Setting the adapter to the ListView */
	    setListAdapter(adapter);
	    
        //ListView selected_courses = (ListView) findViewById(R.id.selected_courses);
        //selected_courses.setAdapter(adapter);
	}
	
	private void getCheckedItems(){
		/** Getting the checked items from the listview */
		SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
		int itemCount = getListView().getCount();
		
		for(int i=itemCount-1; i >= 0; i--){
			if(checkedItemPositions.get(i)){	    				
				adapter.remove(selected.get(i));
			}
		}	
		checkedItemPositions.clear();
	    adapter.notifyDataSetChanged(); 
	}
	  
	
    //---Options Menu---
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.options_main, menu);
        return true;
    }

    public void onPersonaItemClick (MenuItem item) {
    	item.setChecked(!item.isChecked());
    }   
    
    public void onDeleteDoneClick(View v) {
    	courseSelectedListView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId()) {
        //case R.id.search_main:
            //startSearch(null);
            //return true;
        case R.id.generate:
            return true;
        case R.id.delete:
        	courseDeleteListView();
            return true;
        case R.id.options_persona:
            return true;
        case R.id.info:
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    
	
    class ItemAutoTextAdapter extends CursorAdapter
    implements android.widget.AdapterView.OnItemClickListener {

		private DataRetriever mDbHelper;
		
		/**
		 * Constructor. Note that no cursor is needed when we create the
		 * adapter. Instead, cursors are created on demand when completions are
		 * needed for the field. (see
		 * {@link ItemAutoTextAdapter#runQueryOnBackgroundThread(CharSequence)}.)
		 * 
		 * @param dbHelper
		 *            The DataRetriever in use by the outer class
		 *            object.
		 */
		public ItemAutoTextAdapter(DataRetriever dbHelper) {
		    // Call the CursorAdapter constructor with a null Cursor
			super(MainActivity.this, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		    mDbHelper = dbHelper;
		}
		
		/**
		 * Invoked by the AutoCompleteTextView field to get completions for the
		 * current input.
		 * 
		 * NOTE: If this method either throws an exception or returns null, the
		 * Filter class that invokes it will log an error with the traceback,
		 * but otherwise ignore the problem. No choice list will be displayed.
		 * Watch those error logs!
		 * 
		 * @param constraint
		 *            The input entered thus far. The resulting query will
		 *            search for states whose name begins with this string.
		 * @return A Cursor that is positioned to the first row (if one exists)
		 *         and managed by the activity.
		 */
		@Override
		public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
		    if (getFilterQueryProvider() != null) {
		        return getFilterQueryProvider().runQuery(constraint);
		    }
		
		    Cursor cursor = mDbHelper.getCourseName(
		            (constraint != null ? constraint.toString() : null));
		    Log.e("RQBG", "before returning to cursor");
		    return cursor;
		}
		
		/**
		 * Called by the AutoCompleteTextView field to get the text that will be
		 * entered in the field after a choice has been made.
		 * 
		 * @param Cursor
		 *            The cursor, positioned to a particular row in the list.
		 * @return A String representing the row's text value. (Note that this
		 *         specializes the base class return value for this method,
		 *         which is {@link CharSequence}.)
		 */
		@Override
		public String convertToString(Cursor cursor) {
		    final int columnIndex = cursor.getColumnIndexOrThrow("code");
		    final String str = cursor.getString(columnIndex);
		    return str;
		}
		
		/**
		 * Called by the ListView for the AutoCompleteTextView field to display
		 * the text for a particular choice in the list.
		 * 
		 * @param view
		 *            The TextView used by the ListView to display a particular
		 *            choice.
		 * @param context
		 *            The context (Activity) to which this form belongs;
		 *            equivalent to {@code SelectState.this}.
		 * @param cursor
		 *            The cursor for the list of choices, positioned to a
		 *            particular row.
		 */
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
		    final String text = convertToString(cursor);
		    ((TextView) view).setText(text);
		}
		
		/**
		 * Called by the AutoCompleteTextView field to display the text for a
		 * particular choice in the list.
		 * 
		 * @param context
		 *            The context (Activity) to which this form belongs;
		 *            equivalent to {@code SelectState.this}.
		 * @param cursor
		 *            The cursor for the list of choices, positioned to a
		 *            particular row.
		 * @param parent
		 *            The ListView that contains the list of choices.
		 * 
		 * @return A new View (really, a TextView) to hold a particular choice.
		 */
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
		    final LayoutInflater inflater = LayoutInflater.from(context);
		    final View view =
		            inflater.inflate(android.R.layout.simple_dropdown_item_1line,
		                    parent, false);
		
		   return view;
		}
		
		/**
		 * Called by the AutoCompleteTextView field when a choice has been made
		 * by the user.
		 * 
		 * @param listView
		 *            The ListView containing the choices that were displayed to
		 *            the user.
		 * @param view
		 *            The field representing the selected choice
		 * @param position
		 *            The position of the choice within the list (0-based)
		 * @param id
		 *            The id of the row that was chosen (as provided by the _id
		 *            column in the cursor.)
		 */
		@Override
		public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
		    // Get the cursor, positioned to the corresponding row in the result set
		    Cursor cursor = (Cursor) listView.getItemAtPosition(position);
		
		    // Get the state's capital from this row in the database.
		    String capital = cursor.getString(cursor.getColumnIndexOrThrow("code"));
	
		    selected.add(capital);
		    adapter.notifyDataSetChanged();
		}
	}

 
    //---popup---
	/*@SuppressLint("NewApi")
	public void showPopup(View v) {
	    PopupMenu popup = new PopupMenu(this, v);
	    
	    popup.setOnMenuItemClickListener(this);

	    MenuInflater inflater = popup.getMenuInflater();
	    inflater.inflate(R.menu.persona_popup, popup.getMenu());
	    
	    popup.show();
	}*/
	
    
    /** Called when the user clicks the Search button on the Main activity page */
    //public void startSearch(View view) {
      //  Intent intent = new Intent(this, SearchCourse.class);
      //  startActivity(intent);
  //  }
    
    
    // Reference: http://www.androidhive.info/2011/09/how-to-show-alert-dialog-in-android/
    /** Delete confirmation alert dialog*/
    public void deleteConfirmDialog(){ 
	    AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
	    
	    // Setting Dialog Title
	    alertDialog.setTitle(R.string.deleteDialogTitle);
	
	    // Setting Dialog Message
	    alertDialog.setMessage(R.string.deleteDialogMsg);
	
	    // Setting Icon to Dialog
	    alertDialog.setIcon(R.drawable.ic_content_discard);
	
	    // Setting Positive "Yes" Button
	    alertDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog,int which) {
	        	getCheckedItems();
	        	Toast.makeText(getApplicationContext(), "Selected courses deleted", Toast.LENGTH_SHORT).show();
	        }
	    });
	
	    // Setting Negative "NO" Button
	    alertDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	        	dialog.cancel();
	        }
	    });
	
	    // Showing Alert Message
	    alertDialog.show();
    }
}


